27 - Greedy Cow Transport

Python
daily
Course: Introduction to Computational Thinking and Data Science
Published

August 15, 2025

1 6.0002 Problem Set 1: Space Cows Transportation

This is my assignment solution to a part of problemset 1 from this course: Introduction to Computational Thinking and Data Science

1.1 Part A: Transporting Cows

1.1.1 Problem A.1: Loading Cow Data

def load_cows(filename):
    cows = {}
    with open(filename, 'r') as f: # open file
        for line in f: # iterate through each line in txt file
            name, tons = line.strip().split(",") # split line 
            cows[name] = int(tons) # Insert cow name and cow weight into dict
    f.close
    return cows
        
cows = load_cows('data/day27/ps1_cow_data.txt')
cows
{'Maggie': 3,
 'Herman': 7,
 'Betsy': 9,
 'Oreo': 6,
 'Moo Moo': 3,
 'Milkshake': 2,
 'Millie': 5,
 'Lola': 2,
 'Florence': 2,
 'Henrietta': 9}

1.1.2 Problem A.2 Greedy Cow Transport

Result of function should be a list of lists with name of the given cows that can be transported for each run. Each list in the list is a new run

def greedy_cow_transport(cows: dict, max_weight):
    cows_copy = dict(sorted(cows.items(), key=lambda item: item[1], reverse=True))
    transports = []
    

    while len(cows_copy) > 0: # loop while the copy of cows is not empty
        trip = [] # Initialize trip list
        trip_weight = 0 # 
        for cow in list(cows_copy.keys()):              # iterate through a list of the keys in the cows dict (necessary to avoid problem with pop function below
            if (trip_weight+cows_copy[cow]) <= max_weight:              # Check if the total trip weight plus the current cow is less than allowed weight
                trip.append(cow)                    # If the cow fits on the trip, add to trip
                trip_weight += cows_copy[cow]       # add current cow to total weight on trip
                cows_copy.pop(cow) # Remove current cow from the dictionary to not iterate through it again.
        transports.append(trip) # when no more cows fit, append the current trip to transports lists 
    return transports   

Solution

greedy_cow_transport(cows, 10)
[['Betsy'],
 ['Henrietta'],
 ['Herman', 'Maggie'],
 ['Oreo', 'Moo Moo'],
 ['Millie', 'Milkshake', 'Lola'],
 ['Florence']]